package com.tianji.promotion.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;

import static com.tianji.promotion.utils.MyLockType.*;

@Component
public class MyLockFacory {
    private final Map<MyLockType, Function<String, RLock>> lockHandlers;

    public MyLockFacory(RedissonClient redissonClient) {
        this.lockHandlers = new EnumMap<MyLockType, Function<String, RLock>>(MyLockType.class);
        lockHandlers.put(RE_ENTRANT_LOCK, name -> redissonClient.getLock(name));
        lockHandlers.put(FAIR_LOCK, name -> redissonClient.getFairLock(name));
        lockHandlers.put(READ_LOCK, name -> redissonClient.getReadWriteLock(name).readLock());
        lockHandlers.put(WRITE_LOCK, name -> redissonClient.getReadWriteLock(name).writeLock());
    }

    public RLock getLock(MyLockType myLockType, String name) {
        return lockHandlers.get(myLockType).apply(name);
    }
}
